/*
 * Copyright (c) 2024 Huawei Technologies Co.,Ltd.
 *
 * openGauss is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 * http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 * -------------------------------------------------------------------------
 *
 * htap_delete_map.h
 *
 * IDENTIFICATION
 * src/include/storage/htap/htap_delete_map.h
 *
 * -------------------------------------------------------------------------
 */


#ifndef HTAP_DELETE_MAP_H
#define HTAP_DELETE_MAP_H

#include "utils/palloc.h"

namespace htap {
#define BITS_IN_BYTE 8
class HTAPDeleteMap : public BaseObject {
public:
    HTAPDeleteMap();
    virtual ~HTAPDeleteMap();
    virtual void Destroy();

    bool init(uint32_t numOfBits);
    bool set(uint32_t bitIdx);
    bool reset(bool resetToZerro = true);

    void copy(const HTAPDeleteMap &other);
    bool clear(uint32_t bitIdx);
    bool check(uint32_t bitIdx) const;

    uint32_t bitsSigned() const
    {
        return m_bitsSigned;
    }

    unsigned char *htapDeleteMap()
    {
        return m_array;
    }

    uint32_t numOfBits() const
    {
        return m_numOfBits;
    }

    uint32_t firstUnsignedIdx() const
    {
        return m_firstUnsignedIdx;
    }
    void updateFirstUnsignedIdx(uint32_t bitIdx)
    {
        m_firstUnsignedIdx = bitIdx;
    }

private:
    unsigned char *allocate() const;
    inline uint32_t index(uint32_t bitIdx) const
    {
        return bitIdx >> 3;
    }
    inline unsigned char mask(uint32_t bitIdx) const
    {
        return (unsigned char)1 << (bitIdx % 8);
    }
    uint32_t calculateArraySize() const
    {
        return ((uint32_t)m_numOfBits / BITS_IN_BYTE + 1);
    }
    inline bool isInitialized() const
    {
        return (m_numOfBits > 0 || m_array != nullptr);
    }

private:
    unsigned char *m_array;
    uint32_t m_numOfBits;
    uint32_t m_bitsSigned;
    uint32_t m_firstUnsignedIdx;
};
}

#endif // HTAP_DELETE_MAP_H